// 电影管理模块
const { DatabaseManager } = require('./database')
const { generateMovieData } = require('./random-data')

class MovieManager {
  constructor() {
    this.db = new DatabaseManager()
  }

  // 生成电影
  async generateMovies(count, userData) {
    console.log(`🎬 开始生成 ${count} 部电影...`)
    
    const createdMovies = []
    let attempts = 0
    const maxAttempts = count * 3 // 最多尝试3倍次数
    
    while (createdMovies.length < count && attempts < maxAttempts) {
      attempts++
      
      try {
        // 随机选择上传者
        const uploader = userData[Math.floor(Math.random() * userData.length)]
        
        // 生成电影数据
        const movieData = generateMovieData(uploader.authId, uploader.isAi)
        
        // 检查电影是否已存在
        const { data: existingMovie, error: checkError } = await this.db.supabase
          .from('movies')
          .select('id')
          .eq('title', movieData.title)
          .single()
        
        if (existingMovie && !checkError) {
          console.log(`📝 电影 "${movieData.title}" 已存在，跳过`)
          continue
        }
        
        // 只插入movies表中存在的字段，排除country、language、universe等字段
        const { data: movie, error } = await this.db.supabase
          .from('movies')
          .insert({
            title: movieData.title,
            original_title: movieData.original_title,
            cover_url: movieData.cover_url,
            video_url: movieData.video_url,
            rating: movieData.rating,
            year: movieData.year,
            duration: movieData.duration,
            description: movieData.description,
            plot: movieData.plot,
            actors: movieData.actors,
            director: movieData.director,
            uploader_id: movieData.uploader_id,
            views: movieData.views,
            likes: movieData.likes,
            is_ai: movieData.is_ai,
            tags: movieData.tags,
            budget: movieData.budget,
            box_office: movieData.box_office,
            awards: movieData.awards,
            trivia: movieData.trivia
          })
          .select()
          .single()
        
        if (error) {
          console.error(`❌ 创建电影 ${movieData.title} 失败:`, error)
          continue
        }

        // 使用数据库函数设置系统标签
        if (movie.id) {
          console.log(`🏷️  为电影 "${movieData.title}" 设置系统标签...`)
          
          const { data: tagResult, error: tagError } = await this.db.supabase
            .rpc('set_movie_system_tags_simple', {
              p_movie_id: movie.id,
              p_genre_names: movieData.genres.length > 0 ? movieData.genres : null,
              p_universe_name: movieData.universe || null,
              p_language_name: movieData.language || null,
              p_country_name: movieData.country || null
            })

          if (tagError) {
            console.error(`⚠️  设置系统标签失败:`, tagError)
            // 不抛出错误，因为电影已经创建成功
          } else {
            console.log(`✅ 系统标签设置成功:`, tagResult)
          }
        }
        
        createdMovies.push(movie)
        console.log(`✅ 成功创建电影: ${movieData.title} (评分: ${movieData.rating})`)
        
      } catch (error) {
        console.error(`❌ 生成电影时发生错误:`, error)
      }
    }
    
    console.log(`\n📊 电影生成完成: ${createdMovies.length}/${count} 部电影`)
    if (attempts >= maxAttempts) {
      console.log(`⚠️  达到最大尝试次数，停止生成`)
    }
    return createdMovies
  }

  // 为电影添加系统标签
  async addSystemTagsToMovies() {
    console.log('🏷️  为电影添加系统标签...')
    
    try {
      // 获取所有电影
      const { data: movies, error: moviesError } = await this.db.supabase
        .from('movies')
        .select('id, tags')
      
      if (moviesError) {
        throw moviesError
      }
      
      // 获取所有标签
      const { data: tags, error: tagsError } = await this.db.supabase
        .from('tags')
        .select('id, name, category_id')
      
      if (tagsError) {
        throw tagsError
      }
      
      let addedCount = 0
      
      for (const movie of movies) {
        try {
          // 为每部电影添加一些系统标签
          const movieTags = movie.tags || []
          const tagsToAdd = tags.filter(tag => 
            movieTags.some(mt => mt.toLowerCase().includes(tag.name.toLowerCase()))
          ).slice(0, 3) // 最多添加3个系统标签
          
          for (const tag of tagsToAdd) {
            // 检查是否已存在关联
            const { data: existingRelation, error: checkError } = await this.db.supabase
              .from('movie_tags')
              .select('id')
              .eq('movie_id', movie.id)
              .eq('tag_id', tag.id)
              .single()
            
            if (!existingRelation && !checkError) {
              // 添加关联
              const { error: insertError } = await this.db.supabase
                .from('movie_tags')
                .insert({
                  movie_id: movie.id,
                  tag_id: tag.id
                })
              
              if (!insertError) {
                addedCount++
              }
            }
          }
          
        } catch (error) {
          console.error(`❌ 为电影 ${movie.id} 添加标签时发生错误:`, error)
        }
      }
      
      console.log(`📊 系统标签添加完成: ${addedCount} 个关联`)
      return { success: true, addedCount }
    } catch (error) {
      console.error('❌ 添加系统标签时发生错误:', error)
      return { success: false, error: error.message }
    }
  }

  // 获取电影统计信息
  async getMovieStats() {
    try {
      const { data: movies, error } = await this.db.supabase
        .from('movies')
        .select('is_ai, rating, views, likes')
      
      if (error) {
        throw error
      }
      
      const total = movies.length
      const aiMovies = movies.filter(movie => movie.is_ai).length
      const humanMovies = total - aiMovies
      
      const totalRating = movies.reduce((sum, movie) => sum + parseFloat(movie.rating || 0), 0)
      const avgRating = total > 0 ? (totalRating / total).toFixed(1) : '0.0'
      
      const totalViews = movies.reduce((sum, movie) => sum + parseInt(movie.views || 0), 0)
      const totalLikes = movies.reduce((sum, movie) => sum + parseInt(movie.likes || 0), 0)
      
      return {
        success: true,
        stats: {
          total,
          aiMovies,
          humanMovies,
          aiPercentage: total > 0 ? Math.round((aiMovies / total) * 100) : 0,
          avgRating,
          totalViews,
          totalLikes
        }
      }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 清空所有电影
  async clearAllMovies() {
    console.log('🗑️  开始清空所有电影...')
    
    try {
      const { error } = await this.db.supabase
        .from('movies')
        .delete()
        .neq('id', 0)
      
      if (error) {
        throw error
      }
      
      console.log('✅ 电影已清空')
      return { success: true, message: '电影已清空' }
    } catch (error) {
      console.error('❌ 清空电影时发生错误:', error)
      return { success: false, error: error.message }
    }
  }
}

module.exports = MovieManager
